package com.jackson.gson.plugin.jar.adapter

import com.jackson.gson.plugin.global.MyClassPool
import javassist.ClassPool
import javassist.CtClass
import javassist.CtMethod

class InjectReflectiveTypeAdapterFactory {

    static void inject(String dirPath) {

        ClassPool classPool = MyClassPool.getClassPool()

        File dir = new File(dirPath)
        if (dir.isDirectory()) {
            dir.eachFileRecurse { File file ->
                if ("ReflectiveTypeAdapterFactory.class".equals(file.name)) {
                    CtClass ctClass = classPool.getCtClass("com.google.gson.internal.bind.ReflectiveTypeAdapterFactory\$Adapter")
                    CtMethod ctMethod = ctClass.getDeclaredMethod("read")
                    ctMethod.insertBefore("     if (!com.ke.gson.sdk.ReaderTools.checkJsonToken(\$1, com.google.gson.stream.JsonToken.BEGIN_OBJECT)) {\n" +
                            "        return null;\n" +
                            "      }")
                    ctClass.writeFile(dirPath)
                    ctClass.detach()
                    println("GsonPlugin: inject ReflectiveTypeAdapterFactory success")
                }
            }
        }
    }
}
